package com.nami.logic.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import com.nami.logic.utils.ConverTaskUtil;
import com.nami.store.api.request.conversation.ConverItem;
import com.nami.store.api.service.RemoteConverService;
import com.nami.store.api.service.RemoteConverTaskService;
import com.nami.store.api.service.RemoteL2CacheService;
import com.nami.store.api.response.task.ConverTaskDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

import static com.nami.basic.constants.CommonConst.TASK_SEPARATOR;

@Slf4j
@RequiredArgsConstructor
@Service
public class ConverSyncTask {

    private final RemoteConverTaskService taskService;

    private final RemoteConverService converService;

    private final RemoteL2CacheService l2CacheService;

    /**
     * 设置为每台晚上1点同步 或其他节点，慢慢同步
     */
    @Scheduled(cron = "0 0/2 * * * ?")
    public void converSyncTask() {
        try {
            TimeInterval timer = DateUtil.timer();
            log.info("[task] conver sync begin");

            Boolean exist = l2CacheService.isRunningTask("nami:back:task:run");
            if (exist) {
                log.warn("[task] conver sync task is running.");
                return;
            }
            l2CacheService.set("nami:back:task:run", 1);
            int index = 1;
            while (true) {

                List<ConverTaskDTO> result = taskService.getTask(index, 50);
                if (CollUtil.isEmpty(result)) {
                    break;
                }
                for (ConverTaskDTO converTaskDTO : result) {
                    String taskKey = converTaskDTO.getTaskKey();
                    if (StringUtils.isBlank(taskKey)) {
                        continue;
                    }
                    String[] split = taskKey.split(TASK_SEPARATOR);

                    ConverItem conver = converService.getConverFromCache(split[0], split[1], split[2]);
                    if (conver == null) {
                        continue;
                    }
                    converService.insertOrUpd(conver);
                    l2CacheService.delElementByKey(ConverTaskUtil.buildConverItemTaskExistKey(split[0], taskKey));
                }
                List<Long> ids = result.stream().map(ConverTaskDTO::getId).collect(Collectors.toList());
                taskService.batchDel(ids);
                index++;
            }

            log.info("[task] conver sync task done. use time:{}ms", timer.interval());
        } catch (Exception var3) {
            log.error("[task] sync conver error:", var3);
        } finally {
            l2CacheService.delElementByKey("nami:back:task:run");
        }
    }


}
